<?php

// +----------------------------------------------------------------------
// | ShuipFCMS 
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2014 http://www.shuipfcms.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 水平凡 <admin@abc3210.com>
// +----------------------------------------------------------------------

namespace Addon\Sitemaps;

class Sitemaps {

    public function __construct() {
        $this->header = "<\x3Fxml version=\"1.0\" encoding=\"UTF-8\"\x3F>\n\t<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";
        $this->charset = "UTF-8";
        $this->footer = "\t</urlset>\n";
        $this->baidunews_footer = "</document>";
        $this->items = array();
        $this->baidunew_items = array();
    }

    public function add_item2($new_item) {
        $this->items[] = $new_item;
    }

    public function add_baidunews_item($new_item) {
        $this->baidunew_items[] = $new_item;
    }

    public function build($file_name = null) {
        $map = $this->header . "\n";
        foreach ($this->items AS $item) {
            $map .= "\t\t<url>\n\t\t\t<loc>{$item['loc']}</loc>\n";
            $map .= "\t\t\t<lastmod>{$item['lastmod']}</lastmod>\n";
            $map .= "\t\t\t<changefreq>{$item['changefreq']}</changefreq>\n";
            $map .= "\t\t\t<priority>{$item['priority']}</priority>\n";
            $map .= "\t\t</url>\n\n";
        }
        $map .= $this->footer . "\n";
        if (!is_null($file_name)) {
            return file_put_contents($file_name, $map);
        } else {
            return $map;
        }
    }

    public function google_sitemap_item($loc, $lastmod = '', $changefreq = '', $priority = '') {
        $data = array();
        $data['loc'] = $loc;
        $data['lastmod'] = $lastmod;
        $data['changefreq'] = $changefreq;
        $data['priority'] = $priority;
        return $data;
    }

    //百度新闻数组 组成
    public function baidunews_item($title, $link = '', $description = '', $text = '', $image = '', $keywords = '', $category = '', $author = '', $source = '', $pubDate = '') {
        $data = array();
        $data['title'] = $title;
        $data['link'] = $link;
        $data['description'] = $description;
        $data['text'] = $text;
        $data['image'] = $image;
        $data['keywords'] = $keywords;
        $data['category'] = $category;
        $data['author'] = $author;
        $data['source'] = $source;
        $data['pubDate'] = $pubDate;
        return $data;
    }

    /**
     * 返回经htmlspecialchars处理过的字符串或数组
     * @param $obj 需要处理的字符串或数组
     * @return mixed
     */
    public function new_html_special_chars($string) {
        $encoding = 'utf-8';
        if (!is_array($string)) {
            return htmlspecialchars($string, ENT_QUOTES, $encoding);
        }
        foreach ($string as $key => $val) {
            $string[$key] = $this->new_html_special_chars($val);
        }
        return $string;
    }

    public function baidunews_build($file_name = null, $this_domain, $email, $time) {
        //百度头部
        $this->baidunews = '';
        $this->baidunews = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
        $this->baidunews .= "<document>\n";
        $this->baidunews .= "<webSite>" . $this_domain . "</webSite>\n";
        $this->baidunews .= "<webMaster>" . $email . "</webMaster>\n";
        $this->baidunews .= "<updatePeri>" . $time . "</updatePeri>\n";
        foreach ($this->baidunew_items AS $item) {
            $this->baidunews .= "<item>\n";
            $this->baidunews .= "<title>" . $item['title'] . "</title>\n";
            $this->baidunews .= "<link>" . $item['link'] . "</link>\n";
            $this->baidunews .= "<description>" . $item['description'] . "</description>\n";
            $this->baidunews .= "<text>" . $item['text'] . "</text>\n";
            $this->baidunews .= "<image>" . $item['image'] . "</image>\n";
            $this->baidunews .= "<keywords>" . $item['keywords'] . "</keywords>\n";
            $this->baidunews .= "<category>" . $item['category'] . "</category>\n";
            $this->baidunews .= "<author>" . $item['author'] . "</author>\n";
            $this->baidunews .= "<source>" . $item['source'] . "</source>\n";
            $this->baidunews .= "<pubDate>" . $item['pubDate'] . "</pubDate>\n";
            $this->baidunews .= "</item>\n";
        }
        $this->baidunews .= $this->baidunews_footer . "\n";
        if (!is_null($file_name)) {
            return file_put_contents($file_name, $this->baidunews);
        } else {
            return $this->baidunews;
        }
    }

    /**
     * 生成百度新闻
     * @param type $config 配置
     * @return boolean
     */
    public function baidu($config) {
        if (empty($config)) {
            return false;
        }
        $baidunum = $_POST['baidunum'] ? : 20;
        if (empty($config['catids'])) {
            return false;
        }
        $catids = $config['catids'];
        $catid_cache = cache('Category');
        $this_domain = cache('Config.siteurl');
        foreach ($catids as $catid) {
            $modelid = getCategory($catid, 'modelid');
            $result = \Content\Model\ContentModel::getInstance($modelid)->relation(true)->where(array('catid' => $catid, 'status' => 99))->order('id desc')->limit($baidunum)->select();
            foreach ($result as $arr) {
                \Content\Model\ContentModel::getInstance($modelid)->dataMerger($arr);
                if (!preg_match('/^(http|https):\/\//', $arr['url'])) {
                    $arr['url'] = $this_domain . $arr['url'];
                }
                if ($arr['thumb'] != "") {
                    if (!preg_match('/^(http|https):\/\//', $arr['thumb'])) {
                        $arr['thumb'] = $this_domain . $arr['thumb'];
                    }
                }
                //取当前新闻模型 附属表 取 新闻正文
                $arr['url'] = $this->new_html_special_chars($arr['url']);
                $arr['description'] = $this->new_html_special_chars(strip_tags($arr['description']));
                $arr['content'] = $this->new_html_special_chars(strip_tags($arr['content']));
                //组合数据
                $smi = $this->baidunews_item($arr['title'], $arr['url'], $arr['description'], $arr['content'], $arr['thumb'], $arr['keywords'], $arr['category'], $arr['author'], $arr['source'], date('Y-m-d', $arr['inputtime']));
                $this->add_baidunews_item($smi);
            }
        }
        $baidunews_file = SITE_PATH . 'baidunews.xml';
        $this->baidunews_build($baidunews_file, $this_domain, $config['email'], $config['time']);
    }

    /**
     * 生成站点地图
     * @param type $config 配置
     * @return boolean
     */
    public function siteMap($config) {
        if (empty($config)) {
            return false;
        }
        $content_priority = $config['content_priority'];
        $content_changefreq = $config['content_changefreq'];
        $num = $config['num'] ? : 100;
        $today = date('Y-m-d');
        $domain = cache('Config.siteurl');
        //生成地图头部　－第一条
        $smi = $this->google_sitemap_item($domain, $today, 'daily', '1.0');
        $this->add_item2($smi);

        //输出可用模型
        $modelsdata = cache("Model");
        $models = array();
        foreach ($modelsdata as $v) {
            if ($v['disabled'] == 0 && $v['type'] == 0) {
                $new_model[] = $v;
            }
        }
        foreach ($new_model as $m) {//每个模块取出num条数据 
            $modelid = $m['modelid'];
            $result = \Content\Model\ContentModel::getInstance($modelid)->where(array('status' => 99))->limit($num)->order('inputtime desc')->select();
            foreach ($result as $arr) {
                if (substr($arr['url'], 0, 1) == '/') {
                    $url = $this->new_html_special_chars(strip_tags(str_replace($domain . '/', $domain, $domain . $arr['url'])));
                } else {
                    $url = $this->new_html_special_chars(strip_tags($arr['url']));
                }
                if ($arr['views'] > 1000) {
                    $content_priority = 0.9;
                }
                $smi = $this->google_sitemap_item($url, $today, $content_changefreq, $content_priority); //推荐文件
                $this->add_item2($smi);
            }
        }

        $sm_file = SITE_PATH . 'sitemaps.xml';
        if ($this->build($sm_file)) {
            return true;
        }
        return false;
    }

}
